<script setup lang="ts">
defineOptions({
  name: "fabGroup"
});

import { ref, nextTick, inject } from "vue";
import { useRouterStoreHook } from "@/store/modules/router";
import { ArrowLeft } from "@px-ui/icons-vue";
import { useRouter } from "vue-router";
import { queryFabSupplyConsumeFab } from "@/api/modules/fab";
import { useLabelLayoutBarChartFn } from "@/hooks/useEcharts";
import { useStartLoading } from "@/hooks/useCommon";
import { areaes } from "../constant";
import fabAreaItem from "./fabAreaItem.vue";
import dayjs from "dayjs";

const router = useRouter();
const routerStore = useRouterStoreHook();

interface Props {
  params?: Record<string, any> | null;
  selectArea?: string;
}

const props = withDefaults(defineProps<Props>(), {
  params: () => null,
  selectArea: ""
});

const emits = defineEmits(["select"]);

const defaultparameter = inject("defaultparameter", ref<Record<string, any>>({}));
const period = inject("period", ref<string>("week"));

const loading = ref<boolean>(true);
const chambers = ref<Array<any>>([]);
const dataTypes = ref<Array<string>>([]);

const clickHandler = (item: any) => {
  const { label: eqpId = "", options = null } = item;
  if (!options) return;
  const path = "/fullScreen/fab/detail";
  const tab = 1;
  const className = routerStore.getSubject;
  const period_ = period.value;
  const { startTime = "", endTime = "" } = props.params;
  const { name = "", code = "" } = defaultparameter.value;
  const query = { eqpId, tab, period: period_, startTime, endTime, parameter: code, name, className };
  let params = encodeURI(JSON.stringify(query));
  const { href } = router.resolve({ path, query: { params } });
  window.open(href, "_blank");
};

const getOptions = (item?: any, unit?: string) => {
  const { singleDTOList = [], headerInformation = "" } = item;
  const ec = {};
  const xAxisData = singleDTOList.map(item => dayjs(item.dayStr).format("MM/DD"));
  const consumeData = singleDTOList.map(item => item.consumeValue);
  const supplyData = singleDTOList.map(item => item.supplyValue);
  const setData = singleDTOList.map(item => item.setValue);
  const setDataValue = setData.find(item => typeof item === "number");
  const label = {
    show: true,
    position: "top",
    formatter(params) {
      const { dataIndex = 0 } = params;
      if (typeof dataIndex !== "number") return "";
      const { setValue = 0 } = singleDTOList[dataIndex];
      if (typeof setValue !== "number") return "";
      return setValue;
    }
  };
  const legend = {
    show: true,
    right: 0
  };
  const grid = {
    top: 50,
    bottom: 0,
    left: 4,
    right: 40,
    containLabel: true
  };
  const tooltip: any = {
    trigger: "axis",
    axisPointer: {
      type: "shadow"
    }
  };
  const xAxis = [
    {
      type: "category",
      data: xAxisData
      // axisLabel: {
      //   interval: 0
      // }
    }
  ];
  const yAxis = {
    max(value) {
      return Math.ceil(value.max / 100) * 100;
    }
  };
  const setDataSeries = {
    name: "设定值",
    type: "line",
    symbol: "none",
    emphasis: { focus: "series" },
    data: setData,
    itemStyle: {
      color: "#FF4545"
    },
    lineStyle: {
      type: "dashed"
    },
    endLabel: {
      show: true,
      formatter: `${setDataValue}`
    }
  };
  let series: Array<any> = [
    {
      name: "实际值",
      type: "bar",
      // stack: "Ad",
      emphasis: { focus: "series" },
      data: consumeData,
      barGap: "0",
      itemStyle: {
        color: "#3B82F6"
      }
    },
    {
      name: "供给值",
      type: "bar",
      // stack: "Ad",
      emphasis: { focus: "series" },
      data: supplyData,
      barGap: "0",
      itemStyle: {
        color: "#FFCA45"
      }
    }
  ];
  if (typeof setDataValue === "number") {
    series.unshift(setDataSeries);
  }
  series = series.filter(item => dataTypes.value.includes(item.name));
  const ag = { legend, grid, tooltip, xAxis, series };
  return useLabelLayoutBarChartFn(ec, xAxisData, consumeData, headerInformation, unit, null, false, "top", ag);
};

const goBackHandler = () => {
  emits("select");
};

const getChambersList = (res: Record<string, any>): Array<any> => {
  if (!res) return [];
  const { dataDTOS = [], unit = "" } = res;
  const groups = areaes.get(props.selectArea).groups;
  return groups.map((item, index) => {
    const { style, label } = item;
    let options = null;
    const t = dataDTOS[index];
    if (t) {
      options = getOptions(t, unit);
    }
    return {
      style,
      label: t ? t?.headerInformation : label,
      options
    };
  });
};

const init = async (types?: Array<any>) => {
  useStartLoading(loading);
  if (types) {
    dataTypes.value = types;
  }
  await nextTick();
  const res = await queryFabSupplyConsumeFab(props.params, err => {
    loading.value = false;
  });
  const ar = getChambersList(res);
  await nextTick();
  setTimeout(() => {
    chambers.value.splice(0);
    chambers.value.push(...ar);
    loading.value = false;
  }, 0);
};

defineExpose({
  init
});
</script>

<template>
  <div v-loading="loading" class="fab-group">
    <div v-for="item in chambers" :key="item.label" class="fab-group-item" :style="{ ...item.style }">
      <fabAreaItem :data="item" :dataTypes="dataTypes" :defaultparameter="defaultparameter" @click="clickHandler(item)" />
    </div>
    <div class="go-back">
      <px-button type="primary" :icon="ArrowLeft" @click="goBackHandler">返回</px-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.fab-group {
  position: relative;
  width: 100%;
  height: 100%;

  .go-back {
    position: absolute;
    top: 0;
    left: 0;
  }

  .fab-group-item {
    position: absolute;
  }
}
</style>
